package com.example.gateway.config;

import com.example.demo.common.GlobalVariable;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: 故我
 * Date: 2024-02-14
 * Time: 17:26
 */

/**
 * 配置一个全局的过滤器，接收前端传递过来的灰度标志或者和设置灰度标识
 */
@Component
public class LoadBalancer implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 得到 request，response 对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 判断灰度标志
        String target = request.getQueryParams().getFirst(GlobalVariable.GRAY_TAG);
        if (target != null) {
            // 说明有这个灰度标识，向后面的服务进行传递
            response.getHeaders().set(GlobalVariable.GRAY_TAG, "true");
        }

        // 执行下一步
        return chain.filter(exchange);
    }
}
